import fs from 'fs'
import path from 'path'
import { NextFunction, Request, Response } from 'express'
import { controller, get, use } from '../decorator'
import { Crawler, CourseAnalyzer, getResponseData } from '../utils'
const checkLogin = (req: Request, res: Response, next: NextFunction) => {
  const isLogin = !!(req.session ? req.session.login : false)
  if (isLogin) {
    next()
  } else {
    res.json(getResponseData(null, '请先登录'))
  }
}
@controller('/api')
export class CrawlerController {
  @get('/getData')
  @use(checkLogin)
  getData(req: Request, res: Response): void {
    const secret = 'x3b174jsx'
    const url = `http://www.dell-lee.com/typescript/demo.html?secret=${secret}`
    const analyzer = CourseAnalyzer.getInstance()
    new Crawler(analyzer, url, '../../data/course.json')
    res.json(getResponseData<responseResult.getData>(true))
  }

  @get('/showData')
  @use(checkLogin)
  showData(req: Request, res: Response): void {
    const filePath = path.resolve(__dirname, '../../data/course.json')
    if (fs.existsSync(filePath)) {
      const fileContent: responseResult.DataStructure = JSON.parse(
        fs.readFileSync(filePath, 'utf-8')
      )
      res.json(getResponseData<responseResult.showData>(fileContent))
    } else {
      res.json(getResponseData<responseResult.showData>(false, '数据不存在'))
    }
  }
}
